package com.financing.wap.web.controller.api;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailSendException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.financing.mail.dto.MailContentDTO;
import com.financing.mail.service.MailSenderService;
import com.financing.wap.common.CommonConstantUtil;
import com.financing.wap.common.ResultMap;
import com.financing.wap.common.ResultMap.STATUS;
import com.financing.wap.common.Session;
import com.financing.wap.common.SessionUtil;
import com.financing.wap.dto.FpFundBuynoticeDTO;
import com.financing.wap.dto.FpFundCompanyDTO;
import com.financing.wap.dto.FpFundInfoDTO;
import com.financing.wap.dto.FpFundManagerDTO;
import com.financing.wap.dto.ProductAttachmentDTO;
import com.financing.wap.dto.ProductDetailPageDTO;
import com.financing.wap.dto.UserDTO;
import com.financing.wap.service.IFpFundBuynoticeService;
import com.financing.wap.service.IFpFundCompanyService;
import com.financing.wap.service.IFpFundInfoService;
import com.financing.wap.service.IFpFundManagerService;
import com.financing.wap.service.IProductService;
import com.financing.wap.util.MessageUtil;
import com.financing.wap.util.PropertiesUtils;
import com.financing.wap.util.StringUtil;
import com.financing.wap.vo.ProductProfitAndRebateVO;
import com.financing.wap.web.controller.BaseController;

@Controller("sendEmailController")
@RequestMapping("/api/sendEmail")
public class SendEmailController  extends BaseController{
	
	Logger logger = Logger.getLogger(getClass());
	
	@Autowired
	private MailSenderService mailSenderService;
	
	@Autowired
	private IFpFundInfoService fpFundInfoService;
	
	@Autowired
	private IProductService productService;
	
	@Autowired
	private IFpFundBuynoticeService fpFundBuynoticeService;
	
	
	@Autowired
	private IFpFundManagerService fpFundManagerService;
	
	@Autowired
	private IFpFundCompanyService fpFundCompanyService;
	
	public final static Map<String,String> productImgMap;
	
	static{
		productImgMap = new HashMap<String, String>();
		productImgMap.put("bcjscxjh", "保诚 隽升储蓄计划,https://superfa.cn/#/product/oversea-insurance/view?id=bcjscxjh,https://static-superfa-cn.alikunlun.com/upload/bann/20160107/bcqxjh.pdf");
		productImgMap.put("bclxrsbzjh", "保诚理想人生保障计划,https://superfa.cn/#/product/oversea-insurance/view?id=bclxrsbzjh,https://static-superfa-cn.alikunlun.com/upload/bann/20160107/bclxrs.pdf");
		productImgMap.put("cywljh", "AIA-充裕未来储蓄计划,https://superfa.cn/#/product/oversea-insurance/view?id=cywljh,https://static-superfa-cn.alikunlun.com/upload/bann/20160107/cywl.pdf");
		productImgMap.put("aiajtaxb", "AIA-进泰安心保保障计划 ,https://superfa.cn/#/product/oversea-insurance/view?id=aiajtaxb,https://static-superfa-cn.alikunlun.com/upload/bann/20160107/jtaxb.pdf");
		productImgMap.put("ybzzmzylbx", "友邦-至尊明珠医疗保险计划 ,https://superfa.cn/#/product/oversea-insurance/view?id=ybzzmzylbx,https://static-superfa-cn.alikunlun.com/upload/bann/20160107/zzmjyl.pdf");
		
		productImgMap.put("kcyzjbbzjh", "AXA-康采严重疾病保障计划,https://superfa.cn/#/product/oversea-insurance/view?id=kcyzjbbzjh,https://static-superfa-cn.alikunlun.com/upload/bann/20160517/1463468792138kcyzjbbzjh.pdf");
		productImgMap.put("wjzsbjh", "保诚-危疾终生保计划,https://superfa.cn/#/product/oversea-insurance/view?id=wjzsbjh,https://static-superfa-cn.alikunlun.com/upload/bann/20160517/1463468817244wjzsbjh.pdf");
		productImgMap.put("ygcxjh", "大都会-耀光储蓄计划划,https://superfa.cn/#/product/oversea-insurance/view?id=ygcxjh,https://static-superfa-cn.alikunlun.com/upload/bann/20160517/1463468842125ygcxjh.pdf");
		productImgMap.put("cxzcxjh", "宏利-人寿赤霞珠储蓄计划,https://superfa.cn/#/product/oversea-insurance/view?id=cxzcxjh,https://static-superfa-cn.alikunlun.com/upload/bann/20160517/1463468767443cxzcxjh.pdf");
		productImgMap.put("ybawycx", "友邦-爱无忧长享计划3,https://superfa.cn/#/product/oversea-insurance/view?id=ybawycx,https://static-superfa-cn.alikunlun.com/upload/bann/20160517/1463468828055ybawycx.pdf");
	}
	
	/**c
	 * 海外保险列表邮件发送
	 * @param request
	 * @param register
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "/hwbxEmail")
	@ResponseBody
	public ResultMap userPromotion(HttpServletRequest request, String emailAddress,String subject,String pid,
			HttpServletResponse response) throws IOException {
		ResultMap result = new ResultMap();
		try{
			  // 如果前端页面传过来的邮件地址为空，则取当前登陆用户的emailAddress
				if(StringUtil.isNullOrEmptyStr(emailAddress)|| !StringUtil.isEmail(emailAddress)){
					Session session = SessionUtil.getSession();
					UserDTO loginUser = session.getUser();
					if(null != loginUser){
						emailAddress = loginUser.getuEmail();
					}
				}
				
				//如果邮件地址不为空，则发送邮件
				if((!StringUtil.isNullOrEmptyStr(emailAddress))&&StringUtil.isEmail(emailAddress) && (!StringUtil.isNullOrEmptyStr(pid))){
					String productInfo = productImgMap.get(pid);
					if(!StringUtil.isNullOrEmptyStr(productInfo)){
						String[] infos = productInfo.split(",");
						Map<String ,Object> params = new HashMap<String,Object>();
						params.put("productName", infos[0]);
						params.put("productDetailUri",  infos[1]);
						params.put("ziliaoUri",  infos[2]);
						
						MailContentDTO mailContentDTO = new MailContentDTO();
						mailContentDTO.setRecAddress(emailAddress);
						mailContentDTO.setSubject(subject);
						mailContentDTO.setContext(MessageUtil.getMessage("mailTemplate", "hybxMail", params).get(MessageUtil.KEY_CONTENT).toString());
						logger.info("send mail status is "+mailSenderService.send(mailContentDTO));
					}
				}
				
				result.setStatus(STATUS.SUCCESS);
				result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		}catch(Exception e){
			logger.error("send email error:",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return  result;
	}
	

	/**
	 * 信托资管pevc 私募  邮件
	 * @param request
	 * @param register
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "/sendProductInfoEmail")
	@ResponseBody
	public ResultMap sendProductInfoEmail(HttpServletRequest request,HttpServletResponse response) throws IOException {
		ResultMap result = new ResultMap();
		try{
			String pType=request.getParameter("pType");//产品类型
			String pId=request.getParameter("pId");//产品id
			String emailAddress=request.getParameter("emailAddress");
			
			//空校验
			boolean paramNull = StringUtil.isNullOrEmptyNStr(pType,pId,emailAddress);
			if(paramNull){
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				return result;
			}
			//邮箱校验
			boolean email = StringUtil.isEmail(emailAddress);
			if(!email){
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_EMAIL_ERROR);
				return result;
			}
			
			final MailContentDTO mailContentDTO = new MailContentDTO();
			mailContentDTO.setRecAddress(emailAddress);
			
			if("01".equals(pType)){//基金
				FpFundInfoDTO dto = fpFundInfoService.getFpFundInfo(Integer.parseInt(pId));
				if(dto==null||dto.getId()==null){
					result.setStatus(STATUS.ERROR);
					result.setStatusCode(ResultMap.STATUS_CODE_OBJECT_NOFOUNT);
					return result;
				}
				
				//购买须知
				FpFundBuynoticeDTO buynoticeDTO = new FpFundBuynoticeDTO();
				buynoticeDTO.setJjbm(dto.getJjbm());
				buynoticeDTO = fpFundBuynoticeService.getFpFundBuynotice(buynoticeDTO);
				
				Map<String,Object> params=new HashMap<String,Object>();
				params.put("productName", dto.getJjqc());
				String cpqxsm = StringUtils.isBlank(dto.getCpqxsm())?"-":dto.getCpqxsm();
				params.put("cpqxsm", cpqxsm);
				String buynoticedetail = buynoticeDTO.getBuynoticedetail();
				params.put("rgxz", StringUtils.isBlank(buynoticedetail)?"-":buynoticedetail);
				String zdrgje = dto.getZdrgje();
				params.put("rgje", StringUtils.isBlank(zdrgje)?"-":(zdrgje+"万"));
				String productadvantage = dto.getProductadvantage();
				params.put("xmld", StringUtils.isBlank(productadvantage)?"-":productadvantage);
				params.put("jjlx",dto.getJjfl());
				
				//基金公司
				List<FpFundCompanyDTO> companyDTOs = fpFundCompanyService.getFpFundCompanyByFundId(dto.getJjbm());
				if(companyDTOs!=null&&companyDTOs.size()>0){
					FpFundCompanyDTO companyDTO = companyDTOs.get(0);
					params.put("companyName",companyDTO.getGsmc());
				}
				//基金经理
				List<FpFundManagerDTO> managerList = fpFundManagerService.listFpFundManagerByFundId(dto.getJjbm());
				StringBuffer jlName=new StringBuffer();
				for (FpFundManagerDTO fpFundManagerDTO : managerList) {
					jlName.append(","+fpFundManagerDTO.getJjjlmc());
				}
				if(jlName.toString().length()>0){
					params.put("jlName",jlName.substring(1));
				}
				
				String emailContent=MessageUtil.getMessage("allProductEmail", "jijinProductEmail", params).get(MessageUtil.KEY_CONTENT).toString();
				mailContentDTO.setContext(emailContent);
				mailContentDTO.setSubject(dto.getJjmc());
			}else if("02".equals(pType)||"03".equals(pType)||"06".equals(pType)){//信托资管PEVC
				ProductDetailPageDTO dto = productService.getProductDetailView(Integer.parseInt(pId));	
				if(dto==null||dto.getProductId()==null){
					result.setStatus(STATUS.ERROR);
					result.setStatusCode(ResultMap.STATUS_CODE_OBJECT_NOFOUNT);
					return result;
				}
				if(!pType.equals(dto.getProductType())){
					result.setStatus(STATUS.ERROR);
					result.setStatusCode(ResultMap.STATUS_CODE_OBJECT_NOFOUNT);
					return result;
				}
				//拆分字段  切分 
				HashMap<String, String> hm=splitSummary(dto);
				
				
				StringBuffer profitAndRebateStr=new StringBuffer();
				// profitAndRebateList  预期年华返佣
				for (ProductProfitAndRebateVO profitAndRebate : dto.getProfitAndRebateList()) {
					BigDecimal startAmount = profitAndRebate.getStartAmount();
					BigDecimal endAmount = profitAndRebate.getEndAmount();
					BigDecimal startAmountWan = startAmount.divide(new BigDecimal(10000)).setScale(2,BigDecimal.ROUND_HALF_DOWN);
					BigDecimal endAmountWan = endAmount.divide(new BigDecimal(10000)).setScale(2,BigDecimal.ROUND_HALF_DOWN);
					
					profitAndRebateStr.append(startAmountWan.toString())
					.append("-").append(endAmountWan.toString()).append("万元    ")
					.append(profitAndRebate.getExpectAnnualRevenue()).append("  ");
				}
				
				//设置 动态字段
				Map<String,Object> params=new HashMap<String,Object>();
				params.put("productName", dto.getProductName());
				params.put("issuingScale", StringUtil.ObjPrice2Str(dto.getIssuingScale()));
				params.put("dueTime",dto.getDueTime().intValue()+"个月");
				params.put("annualRevenueExpect",profitAndRebateStr.toString());
				String investDesc = CommonConstantUtil.getInvestDesc(dto.getInvestType());
				params.put("investType",investDesc);
				params.put("paymentInterestType", dto.getPaymentInterestTypeDesc());
				String zjyt = hm.get("zjyt");
				params.put("zjyt", StringUtils.isBlank(zjyt)?"-":zjyt);
				String fxkz = hm.get("fxkz");
				params.put("fxkz",  StringUtils.isBlank(fxkz)?"-":fxkz);
				String mjzh = hm.get("mjzh");
				params.put("mjzh",  StringUtils.isBlank(mjzh)?"-":mjzh);
				String xmld = hm.get("xmld");
				params.put("xmld",  StringUtils.isBlank(xmld)?"-":xmld);
				params.put("investOwner", dto.getInvestOwner());
				
				String cpys = hm.get("cpys");
				params.put("cpys",  StringUtils.isBlank(cpys)?"-":cpys);
				
				BigDecimal peSubscriptionFee = dto.getPeSubscriptionFee();
				String fee="";
				if(peSubscriptionFee==null){
					peSubscriptionFee=new BigDecimal(0);
					fee="-";
				}else{
					fee=peSubscriptionFee.doubleValue()+"%";
				}
				params.put("peSubscriptionFee", fee);
				
				String emailContent="";
				if("06".equals(pType)){
					emailContent=MessageUtil.getMessage("allProductEmail", "pevcProductEmail", params).get(MessageUtil.KEY_CONTENT).toString();
				}else{
					emailContent=MessageUtil.getMessage("allProductEmail", "xintuoProductEmail", params).get(MessageUtil.KEY_CONTENT).toString();
				}
				mailContentDTO.setSubject(dto.getProductShortName());
				mailContentDTO.setContext(emailContent);
				
				//产品附件发送
				ProductAttachmentDTO attachment = new ProductAttachmentDTO();
				attachment.setpId(Integer.parseInt(pId));
				List<ProductAttachmentDTO> productAttachments = productService.getProductAttachments(attachment);
				if(productAttachments!=null&&!productAttachments.isEmpty()){
					for(ProductAttachmentDTO productAttachmentDTO:productAttachments){
						String fPath = PropertiesUtils.getValue("fileBaseDir")+productAttachmentDTO.getfPath();
						//发送附件
						mailContentDTO.getFileMap().put(productAttachmentDTO.getfName(),fPath);
					}
				}
			}
			
			
			Thread t=new Thread(new Runnable() {
				public void run() {
					try {
						mailSenderService.send(mailContentDTO);
					} catch (MailSendException e) {
						logger.error("send Email error",e);
					}
				}
			});
			t.start();
		
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		}catch(Exception e){
			logger.error("send email error:",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return  result;
	}
	
}
